package com.kk.xhr.admin.aop;

import com.kk.xhr.common.pojo.AuthUser;
import com.kk.xhr.web.util.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 操作日志aop
 *
 * @author kkmystery
 * @version 1.0 2021/3/30
 * @since 1.0.0
 */
@Aspect
@Component
@Lazy(false)
@Slf4j
public class LogAspect {

    @Pointcut("execution(* com.kk.xhr.admin.controller.*.*(..))")
    private void pointCut() {}

    @Before("pointCut()")
    public void log(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        AuthUser authUser = ShiroUtil.getAuthUser();
        if (null == authUser) {
            authUser = new AuthUser()
                .setUsername("anno");
        }
        log.info("user: {}, url:{}, method:{}, ip:{}, class_method:{}, args:{}",
            authUser.getUsername(), request.getRequestURL(), request.getMethod(), request.getRemoteAddr(),
            joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
            Arrays.asList(joinPoint.getArgs()));
    }
}
